import re

RE_PREFIX = re.compile(r"[=@^]")


class PlaceholderMixin:
    """自动添加搜索框提示文字"""

    change_list_template = "custom_admin/change_list.html"

    def changelist_view(self, request, extra_context=None):
        if search_placeholder := getattr(self, "search_placeholder", False):
            extra_context = extra_context or {}
            if search_placeholder is True:
                if fs := getattr(self, "search_fields", None):
                    meta = self.model._meta
                    names = []
                    for field in fs:
                        field = RE_PREFIX.sub("", field)
                        if "__" not in field:
                            names.append(meta.get_field(field).verbose_name)
                        else:
                            fn, nxt, *_ = field.split("__")
                            f_obj = meta.get_field(fn)
                            related_model = f_obj.remote_field.model
                            r_n = related_model._meta.get_field(nxt).verbose_name
                            if (n := getattr(f_obj, "verbose_name", "")) != r_n:
                                n += r_n
                            names.append(n)
                    search_placeholder = "请输入 " + "/".join(names)
            extra_context["search_placeholder"] = search_placeholder
        return super().changelist_view(request, extra_context)
